/**
 * 测试线程相关函数 pthread_exit；
 * @author: sundx
 * @date: 2020-05-24 03:20:35
 * @Last Modified by: sundx
 * @Last Modified time: 2020-05-24 14:35:52
 */
#include <iostream>
#include <pthread.h>
#include <unistd.h>
void *demo(void *m);
void outError(const char *errorMessage);
int main() {
  pthread_t tid;
  int ret, i;
  std::cout << "main pid: " << getpid() << " tid: " << pthread_self()
            << std::endl;
  // std::cout << sizeof(void *) << " " << sizeof(int) << std::endl;
  for (i = 0; i < 5; ++i) {
    ret = pthread_create(&tid, NULL, demo, (void *)i); //传值，借助强转；
    if (ret != 0) {
      outError("pthread failed");
    }
    // std::cout << i << std::endl;
  }

  // sleep(i); // 等待线程
  pthread_exit(nullptr);
  // return 0;
}
void *demo(void *m) {
  long i = (long)m; //使用8字节long，防止丢失精度；
  sleep(i + 1);
  std::cout << m << " " << i + 1 << " pid: " << getpid()
            << " tid: " << pthread_self() << std::endl;
  return nullptr;
}
void outError(const char *errorMessage) {
  std::cout << errorMessage << std::endl;
  exit(EXIT_FAILURE);
}